<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="app">
        <h3>您要购买的书籍</h3>
        <li v-for="(item, index) in arr" :key="index">
            <span>{{item.name}}</span>
            <button @click="addfn(item)">买书</button>
        </li>
       <hr>
       <li v-for="(item, index) in pusharr" :key="item.name">
           <span>{{item.name}}</span>
           <span>{{item.price}}</span>
           <button @click="del(index)">-</button>
           <span>{{item.num}}</span>
            <button @click="addnum(index)">+</button>
        
           <span>{{item.num * item.price}}</span>

       </li>
       <h1>总价:{{sum}}</h1>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el: '#app',
            data: { // 响应式的变量
               arr : [
                   {
                       name:"水浒传",
                       price:107,
                       num:1
                   },
                   {
                       name:"西游记",
                       price:100,
                       num:1
                   },
                   {
                       name:"红楼梦",
                       price:200,
                       num:1
                   },
                   {
                       name:"三国演义",
                       price:300,
                       num:1
                   },
               ],
               pusharr:[ ],
               sum : 0 , // 保存计算的总价
            },
            methods: {
                addfn(item) {
                    console.log(item);
                    this.pusharr.push(item)
                    this.pusharr = Array.from(new Set ( this.pusharr)) // 数组的去重
                    console.log(this.pusharr);
                },
                addnum (index) {
                    console.log(index);
                    this.pusharr[index].num++
                },
                del (index) {
                    this.pusharr[index].num -- 
                    if (  this.pusharr[index].num <= 1 ) {
                        this.pusharr[index].num = 1
                    }
                }
            },
            watch: { // 侦听器
                pusharr: {
                    deep: true,
                    immediate: true,
                    handler(newVal, oldVal) {
                        console.log("render");
                        this.sum = newVal.reduce((a,b)=>{
                            return a + b.price * b.num
                        },0)

                    },
                },
            },
        })
    </script>
</body>

</html>